<template>
  <el-row style="height:100%">
    <page report="true">
      <div class="report-header">
        <div class="head-row">
          <span class="choice-title">所属企业：</span>
          <el-cascader
            v-model="company_id_arr"
            :placeholder="'选择所属企业'"
            collapse-tags
            :options="optionsCom"
            ref="cascaderRef"
            :props="{
              expandTrigger: 'hover',
              multiple: 'true',
            }"
            @visible-change="companyVisibleChange"
            @remove-tag="companyRemoveTag"
            size="small"
            style="width:400px">
          </el-cascader>
          <span class="choice-title" style="margin-left:20px">案场选择：</span>
          <el-select
            v-model="case_id"
            @change="CaseChange"
            ref="caseRef"
            filterable
            size="small"
            placeholder="请选择案场"
            style="width:400px;display: inline-block">
            <el-option
              v-for="item in optionsCase"
              :key="item.id"
              :label="item.case_name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="head-row">
          <span class="choice-title">日期选择：</span>
          <el-date-picker
            v-model="datetimeval"
            type="daterange"
            @change="changeDate"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            align="right"
            style="width: 500px;">
          </el-date-picker>
        </div>
        <div class="head-row ok">
          <el-button @click="Updata" class="queryReport"
                     :type="dataIsChange ? 'primary':'success'" size="small">
            <span v-if="dataIsChange"><i class="el-icon-search"></i> 查询排行</span>
            <span v-else><i class="el-icon-refresh-left"></i> 刷新排行</span>
          </el-button>
        </div>
        <div class="hei13"></div>
        <el-tabs v-model="indicator_key" type="card" @tab-click="Updata" style="max-height: 1000px">
          <el-tab-pane label="客流" name="face_total_enters"></el-tab-pane>
          <el-tab-pane label="会员" name="face_member_enters"></el-tab-pane>
          <el-tab-pane label="回头客" name="face_repeats_enters"></el-tab-pane>
        </el-tabs>
        <el-input placeholder="请输入店铺名称" v-model="areaName" size="small" style="width: 300px;margin: 10px">
          <el-button slot="append" icon="el-icon-search" @click="searchAreaName"></el-button>
        </el-input>
        <el-button size="small" tyep="primary" @click="exportExcel">导出</el-button>
        <el-table :data="showTableData" id="rankTable" size="small" spripe max-height="800">
          <el-table-column label="排名" prop="rank" width="60" align="center"></el-table-column>
          <el-table-column label="店铺名" prop="area_name" align="center"></el-table-column>
          <el-table-column label="累计客流量" prop="person_count" align="center" width="120"></el-table-column>
          <el-table-column label="日均客流量" prop="average_per_day" align="center" width="120"></el-table-column>
          <el-table-column label="性别分布" prop="sex" align="center"></el-table-column>
          <el-table-column label="主要客群年龄段" prop="rank" align="center">
            <template slot-scope="scope">
              <span>
                {{scope.row.maxAgeList}}
                <el-popover
                  placement="top-start"
                  width="200"
                  trigger="hover">
                  <ul>
                    <li v-for="item in scope.row.ageList">{{item}}</li>
                  </ul>
                  <i class="el-icon-info" slot="reference"></i>
                </el-popover>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="客流增长率" prop="trend_rate" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.trend_rate">
                {{scope.row.trend_rate}}%
                <el-popover
                  placement="top-start"
                  width="200"
                  trigger="hover">
                  <span>环比增长率=（本期客流 - 上期客流）/ |上期客流|</span>
                  <i class="el-icon-info" slot="reference"></i>
                </el-popover>
              </span>
              <span v-else>——</span>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center;margin-top: 20px">
          <el-button v-if="tableData.length>10 && !isShowAll"
                     @click="showAllTableData"
                     size="small" tyep="primary">显示全部数据</el-button>
        </div>
      </div>

    </page>
  </el-row>

</template>
<style lang="scss" scoped>
  .report-header{
    width: 100%;
    background: #fff;
    padding: 27px 0 20px 45px;
    .head-row{
      line-height: 36px;
      height: 36px;
      margin-bottom: 15px;
      .choice-title{
        display: inline-block;
        width: 85px;
        margin-right: 5px;
        text-align: left;
      }
      &.ok {
        height: auto;
        min-height: 36px;
        line-height: 36px;
        text-align: center;
        .el-radio-group{
          height: 36px;
          line-height: 36px;
          .el-radio-button__inner {
            height: 36px;
            line-height: 36px;
            padding: 0;
            width: 50px;
            font-size: 12px;
          }
        }
        .queryReport {
          line-height: 36px;
          height: 36px;
          padding: 0 10px;
          margin-right: 45px;
          vertical-align: middle;
          display: inline-block;
          // background-color: #8EC5FC;
          // background-image: linear-gradient(62deg, #8EC5FC 0%, #E0C3FC 100%);
          // border-color: #8EC5FC;
          background:#545deb;border-color:#545deb;
          &.el-button--success{
            background: #85ce61;
            border-color: #85ce61;
          }
          span{
            color:#fff;
          }
        }
      }
    }
  }
</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import pageheader from "@/components/page/pageheader";
  import reportGlobal from "@/components/global/reportGlobal";//公共配置
  let kpiName = reportGlobal.name;
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
  export default {
    data() {
      return {
        tableData:[],
        showTableData:[],
        ageList:[],
        company_id_arr:[],
        optionsCom:[],
        case_id:'',
        optionsCase:[],
        indicator_key:'face_total_enters',
        globalIndicator_keys:[],
        tags:2,
        areaName:'',
        datetimeval:[moment(new Date()).subtract(6, 'days').format("YYYY-MM-DD"),moment(new Date()).format("YYYY-MM-DD")],
        dataIsChange:true,
        isShowAll:false,
        pickerOptions: {                //时间日期控件规则
          disabledDate(time) {
            return time.getTime() > Date.now();   //正常 今天之前
          },
        },
        global: {},//公共参数
        code: this.$route.query.code,        //通过菜单栏点击传过来的code判断使用的公共参数
      }
    },
    components: {
      page,
      pageheader,
    },
    created(){
      for (let i in reportGlobal.queryList) {
        if (this.code == reportGlobal.queryList[i].code) {
          this.global = reportGlobal.queryList[i]
        }
      }
      this.globalIndicator_keys = this.global.indicator_keys
      this.getReady()
    },
    computed:{
      tables: function () {
        let search = this.search;
        if (search) {
          return this.tableData.filter(function (dataNews) {
            return Object.keys(dataNews).some(function (key) {
              if(key.includes('id'))
              {
                return false;
              }
              return String(dataNews[key]).toLowerCase().indexOf(search) > -1
            })
          })
        }
        return this.tableData
      },
    },
    methods:{
      //
      getReady(){
        let asyncFun = async ()=>{
          await this.getAgeList();
          await this.getCompany();
          await this.getCase()
        }
        asyncFun().then(data=>{
          this.dataIsChange=true;
        })
        .catch(err=>{
          console.log(err);
          this.$message.warning(err);
        })
        this.$Bus.$emit('Loading',false);
      },
      //获取年龄组配置
      getAgeList(){
        let p = new Promise((res,rej)=>{
          let url = '/sys/face_report/age_group'
          this.$api.post(url)
          .then(data=>{
            // console.log(data);
            this.ageList = data.data;
            res()
          })
          .catch(err=>{
             console.log(err);
            this.$message.error('获取年龄组失败')
            rej()
          })
        })
        return p
      },

      //获取企业树
      getCompany(){
        let p = new Promise((res,rej)=>{
          let url = '/sys/report_assist_new/company_tree';
          this.$api.get(url)
          .then(data => {
            if(data){
              recursion(data.data);
              function recursion(val) {
                if(val.length){
                  for(let i in val){
                    val[i].value = val[i].id;
                    val[i].label = val[i].company_name;
                    val[i].parent_id_str = val[i].parent_name_list ? val[i].parent_name_list.join('/') : '';
                    if(val[i].children && val[i].children.length){
                      recursion(val[i].children)
                    }else{
                      delete val[i].children
                    }
                  }
                }
              }
              this.$nextTick(()=>{
                let arr = [];
                recursionData(Array.of(data.data[0]))
                function recursionData(val) {
                  if(val.length){
                    for(let i in val){
                      if(val[i].children){
                        recursionData(val[i].children)
                      }else{
                        arr.push(val[i].node_location.split('-').slice(0,-1))
                        delete val[i].children
                      }
                    }
                  }
                }
                this.optionsCom = data.data;
                let company_id_arr = [];//配置当前第一个选中的值
                arr.map(x=>{
                  for(let i = 0 ; i < x.length;i++){
                    if(x[i] == data.data[0].id){
                      company_id_arr.push(x.slice(i,x.length))
                    }
                  }
                });
                this.company_id_arr = company_id_arr;
                this.company_id = company_id_arr.join(',');
                res();
              })
            }
          })
          .catch(err=>{
            this.optionsCom = [];
            this.optionsCase = [];
            this.company_id_arr = [];
            this.company_id = null;
            this.case_id = [];
            rej('未获取到企业树')
          })
        })
        return p
      },
      //获取案场
      getCase(){
        let p = new Promise((res,rej)=>{
          let lsarr=[];
          let company_id_arr = this.company_id_arr
          for(let i in company_id_arr) {
            lsarr.push(company_id_arr[i][company_id_arr[i].length-1])
          }
          let params={
            org_id_list:lsarr,
            org_type:1
          }
          let url='/sys/report_assist_new/case_list'
          this.$api.post(url,params)
          .then(data=>{
            this.optionsCase = [];
            this.case_id = '';
            if(data.data && data.data.length){
              this.optionsCase = data.data;
              this.case_id = data.data[0].id;
              res();
            } else{
              this.optionsCase = [];
              this.case_id = '';
              rej('该企业下无案场')
            }
          })
          .catch(err=>{
            this.optionsCase = [];
            this.case_id = '';
            rej('该企业下无案场')
          })
        })
        return p
      },

      companyVisibleChange(val){
        if(!val){
          this.companyChange();
        }
      },
      companyRemoveTag(){
        this.$nextTick(()=>{
          if(this.company_id_arr.length) this.companyChange();
        })
      },
      companyChange(){
        if(!this.company_id_arr.length) {
          this.case_id='';
          this.optionsCase=[];
          this.$message.warning('请至少选择一个企业');
          return
        }
        let company_id_arr = this.company_id_arr.map(x => {
          return x.slice(-1)[0]
        });
        this.company_id = company_id_arr.join(',')
        this.getCase();
        this.dataIsChange=true;
        this.defaultState()
      },
      CaseChange(){
        console.log();
        this.dataIsChange=true;
        this.defaultState()
      },
      changeDate(val){
        console.log(val);
        this.dataIsChange=true;
        this.defaultState()
      },
      defaultState(){
        this.tableData= [];
        this.showTableData = []
      },
      Updata(){
        if(!this.case_id){
          this.$message.warning('请选择案场')
          return;
        }
        if(!this.datetimeval){
          this.$message.warning('请选择日期')
          return;
        }
        this.$Bus.$emit('Loading', true)
        this.isShowAll = false
        this.dataIsChange = false
        this.defaultState()

        let params = {
          org_id_list:Array.of(this.case_id),
          org_type:2
        }

        let start_day = this.datetimeval[0];
        let end_day =  this.datetimeval[1];
        let start_hm =  '00:00';
        let end_hm =  '23:59';

        let url = '/sys/face_report/face_area_ranking_list?indicator_key='+ this.indicator_key + '&tags=' + this.tags +
        '&start_day='+ start_day + '&end_day=' + end_day + '&start_hm=' + start_hm + '&end_hm='+ end_hm
        this.$api.post(url,params)
        .then(data=>{
          console.log(data)
          if(data.data && data.data.length){
            let diff = moment(end_day).diff(moment(start_day),'days') + 1//获取相差天数
            this.tableData = data.data.map((x,i)=>{
              x.rank = '第'+ (i+1);
              x.average_per_day = Math.round(x.person_count / diff)
              x.sex = `男${((x.male_count/x.person_count)*100).toFixed(2) }% / 女${((x.female_count/x.person_count)*100).toFixed(2) }%`
              let maxAgeList = this.sortObj(x.age_group_count)
              console.log(maxAgeList,'maxAgeList');
              x.ageList = []
              for(let i in this.ageList){
                for(let j in x.age_group_count){
                  if(this.ageList[i].key == j){
                    x.ageList.push(`${this.ageList[i].info}(${ ((x.age_group_count[j]/x.person_count)*100).toFixed(2)}%)-${x.age_group_count[j]}人`)
                  }
                }
                if(maxAgeList[this.ageList[i].key]){
                  x.maxAgeList = `${this.ageList[i].info}(${ ((maxAgeList[this.ageList[i].key]/x.person_count)*100).toFixed(2)}%)-${maxAgeList[this.ageList[i].key]}人`
                }
              };
              console.log(x);
              return x
            })

            this.$nextTick(()=>{
              this.showTableData = this.tableData.filter((x,i)=>{
                return i < 10
              })
            })

          }
          this.$Bus.$emit('Loading', false)
        })
        .catch(err=>{
          console.log(err);
          this.$Bus.$emit('Loading', false)
        })
      },
      //获取到最大值
      sortObj(obj){
        const keys = Object.keys(obj).sort(function(a, b) { return obj[a] < obj[b] ? 1 : -1})
        var newObj = {}
        newObj[keys[0]] = obj[keys[0]]
        return newObj
      },
      showAllTableData(){
        this.isShowAll = true
        this.showTableData = this.tableData
      },
      searchAreaName(){
        if(this.areaName){
          this.showTableData = this.tableData.filter(x=>{
            return x.area_name.includes(this.areaName)
          });
          this.isShowAll = true
        }else{
          this.showTableData = this.tableData.filter((x,i)=>{
            return i < 10
          })
          this.isShowAll = false
        }
      },
      exportExcel(){
        if(this.tableData.length){
          /* generate workbook object from table */
          let id = '#rankTable';
          let wb;
          let fix = document.querySelector('.el-table__fixed');
          if (fix) {
            wb = XLSX.utils.table_to_book(document.querySelector(id).removeChild(fix));
            document.querySelector(id).appendChild(fix);
          } else {
            wb = XLSX.utils.table_to_book(document.querySelector(id));
          }
          /* get binary string as output */
          let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
          let name = `${this.$refs.caseRef.selectedLabel}-${kpiName[this.indicator_key]}-${this.datetimeval[0]}至${this.datetimeval[1]} 店铺排行`
          console.log(name,'name');
          try {
            FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), name + '.csv');
          } catch (e) {
            if (typeof console !== 'undefined') console.log(e, wbout)
          }
          return wbout
        }
      }
    }
  }
</script>

<style>
</style>